package com.example.myapplication.mine

import android.util.Log
import androidx.annotation.StringRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.R
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.withLink
import androidx.compose.ui.text.withStyle

@Composable
fun LoginMainScreen() {

    val focusManager = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current
    //用户协议和隐私政策的url处理
    val uriHandler = LocalUriHandler.current

    //用户名和手机号
    val userNameFocusRequester = remember { FocusRequester() }
    val passwordFoucusRequester = remember { FocusRequester() }

    //用户协议和隐私政策
    var isAgreePrivacy by remember {
        mutableStateOf(false)
    }
    //用户协议和隐私政策部分完成，用户协议和隐私政策部分可实现富文本功能，并且支持可点击跳转功能
    val annotatedText = buildAnnotatedString {
        append("我已阅读并同意")

        //添加服务政策
        withLink(
            LinkAnnotation.Url(
                "https://www.baidu.com",
                TextLinkStyles(style = SpanStyle(color = Color(0xff4A90E2)))
            ) { it -> //用户协议点击跳转的回调处理
                println("url链接is----${it}")
                val url = (it as LinkAnnotation.Url).url
                uriHandler.openUri(url)
            }
        ) {
            append("《用户协议》")
        }

        append("和")

        //添加隐私政策
        withLink(
            LinkAnnotation.Url(
                "privacy",
                TextLinkStyles(style = SpanStyle(color = Color(0xff4A90E2)))
            ) {//隐私政策点击跳转的回调处理
                println("url链接is----${it}")

            }) {
            append("《隐私政策》")
        }
    }


    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures {
                    focusManager.clearFocus()
                    keyboardController?.hide()
                }
            }) {
        Image(
            painter = painterResource(id = R.drawable.login_title_icon),
            contentDescription = "login title icon",
            modifier = Modifier
                .width(61.dp)
                .padding(top = 86.dp)
        )

        //输入用户名，密码的输入框，以及同意相关隐私政策区域
        Column(modifier = Modifier.padding(top = 80.dp)) {
            MyTextField(
                modifier = Modifier
                    .padding(top = 24.dp, start = 16.dp, end = 16.dp)
                    .fillMaxWidth(),
                focusRequester = userNameFocusRequester,
                placeHolderResourceString = R.string.userInputUserName
            )

            MyTextField(
                modifier = Modifier
                    .padding(top = 24.dp, start = 16.dp, end = 16.dp)
                    .fillMaxWidth(),
                focusRequester = passwordFoucusRequester,
                placeHolderResourceString = R.string.userinputPasswd,
                isAllowSecurityMode = true
            )

            Row(
                modifier = Modifier
                    .padding(top = 32.dp, start = 16.dp)
                    .height(30.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    painter = painterResource(if (!isAgreePrivacy) R.drawable.privacy_and_service_checkbox_off else R.drawable.privacy_and_service_checkbox_on),
                    contentDescription = "选择框",
                    modifier = Modifier
                        .width(16.dp)
                        .height(16.dp)
                        .clickable(onClick = {
                            isAgreePrivacy = !isAgreePrivacy
                        })
                )

                //"我已阅读并同意《服务条款》和 《隐私政策》"
                Text(
                    text = annotatedText,
                    fontSize = 12.sp,
                    modifier = Modifier.padding(start = 8.dp),
                    lineHeight = 30.sp
                )
            }
        }

        //登陆按钮
        Button(
            onClick = {
                print("login btn is clicked")
            },
            modifier = Modifier
                .padding(top = 40.dp, start = 16.dp, end = 16.dp)
                .fillMaxWidth()
                .height(44.dp),
            shape = RoundedCornerShape(4.dp),
            colors = ButtonColors(
                containerColor = Color(0xff4A90E2),
                contentColor = Color.White,
                disabledContainerColor = Color(0xff4A90E2),
                disabledContentColor = Color.White
            )
        ) {
            Text(stringResource(R.string.loginText))
        }

        //新用户注册 ｜ 忘记密码
        Row(
            modifier = Modifier
                .padding(start = 16.dp, end = 16.dp, top = 30.dp)
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            TextButton(
                onClick = {
                    Log.e("loginIn", "新用户注册")
                },
                colors = ButtonColors(
                    contentColor = Color(0xff6B7280),
                    containerColor = Color.Transparent,
                    disabledContentColor = Color(0xff6B7280),
                    disabledContainerColor = Color.Transparent
                )
            ) {
                Text(stringResource(R.string.newUserReigster), fontSize = 14.sp)
            }

            Text(
                "|",
                color = Color(0xffD1D5DB),
                lineHeight = 16.sp,
                modifier = Modifier.width(1.dp)
            )

            TextButton(
                onClick = {
                    Log.e("loginIn", "忘记密码")
                },
                colors = ButtonColors(
                    contentColor = Color(0xff6B7280),
                    containerColor = Color.Transparent,
                    disabledContentColor = Color(0xff6B7280),
                    disabledContainerColor = Color.Transparent
                )
            ) {
                Text(stringResource(R.string.forgetLoginPasswd), fontSize = 14.sp)
            }
        }

        //占据剩余空间
        Box(modifier = Modifier.weight(1.0f))

        //其它登陆方式
        Column(modifier = Modifier.padding(bottom = 40.dp)) {
            Row(modifier = Modifier.padding(horizontal = 33.dp).height(20.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                Box(modifier = Modifier.padding(end = 16.dp).weight(1.0f).height(1.dp).background(color = Color(0xffE5E7EB)))
                Text("其它登陆方式", fontSize = 14.sp, color = Color(0xffE5E7EB))
                Box(modifier = Modifier.padding(start = 16.dp).weight(1.0f).height(1.dp).background(color = Color(0xffE5E7EB)))
            }

            Row(modifier = Modifier.padding(top = 16.dp).fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
                IconButton(onClick = {
                    Log.e("login","使用微信登陆")
                }) {
                    Icon(painter = painterResource(R.drawable.login_with_wechat), modifier = Modifier.size(40.dp), contentDescription = "使用微信登陆", tint = Color(0xff9CA3AF))
                }

                IconButton(onClick = {
                    Log.e("login","使用QQ登陆")
                }, modifier = Modifier.padding(start = 32.dp)) {
                    Icon(painter = painterResource(R.drawable.login_with_qq), modifier = Modifier.size(40.dp), contentDescription = "使用QQ登陆",tint = Color(0xff9CA3AF))
                }

                IconButton(onClick = {
                    Log.e("login","使用微信登陆")
                },modifier = Modifier.padding(start = 32.dp)) {
                    Icon(painter = painterResource(R.drawable.login_with_sina), modifier = Modifier.size(40.dp), contentDescription = "使用新浪登陆",tint = Color(0xff9CA3AF))
                }
            }
        }
    }
}


@Composable
fun MyTextField(
    modifier: Modifier,
    focusRequester: FocusRequester,
    @StringRes placeHolderResourceString: Int,
    isAllowSecurityMode: Boolean = false
) {
    var textStr by remember { mutableStateOf("") }
    var isFocused by remember { mutableStateOf(false) }
    var isShowPassword by remember { mutableStateOf(false) }

    // 获取焦点管理器和键盘控制器
    val focusManafocusManagerger = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current

    BasicTextField(
        value = textStr,
        modifier = Modifier
            .focusRequester(focusRequester)
            .onFocusChanged { state ->
                Log.e("LoginMain", "state is ${state.isFocused}")
                isFocused = state.isFocused
            },
        onValueChange = { str ->
            println("str is $str")
            textStr = str
        },
        singleLine = true,
        keyboardActions = KeyboardActions(onDone = {
            focusManafocusManagerger.clearFocus()
            keyboardController?.hide()
        }),
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        visualTransformation = if (isShowPassword || !isAllowSecurityMode) VisualTransformation.None else PasswordVisualTransformation(
            '*'
        ),
        decorationBox = { innerTextField ->
            Box(
                modifier = modifier
                    .height(44.dp)
                    .border(
                        width = 1.dp,
                        color = Color(0xFFE5E7EB),
                        shape = RoundedCornerShape(12.dp)
                    )
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxSize()
                ) {
                    Icon(
                        painter = painterResource(R.drawable.login_main_user),
                        contentDescription = "",
                        modifier = Modifier
                            .padding(horizontal = 15.dp)
                            .width(13.dp)
                            .height(14.dp)
                    )
                    Row(modifier = Modifier.weight(1f)) {
                        if (textStr.isEmpty() && !isFocused) {
                            Text(
                                stringResource(placeHolderResourceString),
                                color = Color(0xFF9CA3AF),
                                fontSize = 14.sp
                            )
                        } else {
                            innerTextField()
                        }
                    }
                    if (isAllowSecurityMode) {//是否有隐藏和显示的icon
                        Icon(
                            painter = painterResource(if (isShowPassword) R.drawable.show_real_password_icon else R.drawable.hide_real_password_icon),
                            contentDescription = "",
                            modifier = Modifier
                                .width(33.dp)
                                .height(21.dp)
                                .padding(end = 15.dp)
                                .clickable(onClick = {
                                    isShowPassword = !isShowPassword
                                }),
                        )
                    }
                }
            }
        }
    )
}